//
//  KDMRelationController.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/11/13.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "KDMRelationController.h"
#import "GBSingleWebViewController.h"
#import "KDReportController.h"
#import "KDMListCellBaseModel.h"
#import "KDRelationCell.h"
#import "KDPatrolgetReportParam.h"
#import "KDGetMonitorListParam.h"
#import "KDMonitorRequestTool.h"
#import "KDMKeywordMonitorResult.h"
//#define ServerActionAddr3 @"http://192.168.1.221/mlist_image.html?"
//#define ServerActionAddr2 @"http://ql.yunyq.cn/mlist_image.html?"
#define DURATION 0.8
#define SCROLL_H 420
#define SEGMENT_H 40
#define WEBVIEW_TAG 888
@interface KDMRelationController ()<UIWebViewDelegate, UITableViewDelegate, UITableViewDataSource, KDRelationCellDelegate>
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIWebView *webView1;
@property (nonatomic, strong) UIScrollView *scrollView;
/**
 *  加载第几页
 */
@property (nonatomic, strong) NSString *page;
@property (nonatomic, weak) UISegmentedControl *segment;
/**
 *  当前是第几页
 */
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) NSArray *infoArr;
@property (nonatomic, weak) UIView *headView;
/**
 *  媒体url
 */
@property (nonatomic, copy) NSString * mediaUrl;
/**
 *  网站Url
 */
@property (nonatomic, copy) NSString * webUrl;

@end

@implementation KDMRelationController
- (NSArray *)infoArr
{
    if (!_infoArr) {
        _infoArr = [NSArray new];
    }
    return _infoArr;
}
- (NSString *)page
{
    if (!_page) {
        _page = @"1";
    }
    return _page;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BackGroundColor;
    [self setUpTableView];
}
/**
 *  初始化segment
 */
- (void)setuUpSegment{
    UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:@[@"媒体分布图", @"网站来源统计"]];
    segment.frame = CGRectMake(40, 15, screenW - 40*2, SEGMENT_H);
    segment.tintColor = KDHeadColor;
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:18],NSFontAttributeName,nil];
    [segment setTitleTextAttributes:dic forState:UIControlStateNormal];

    self.segment = segment;
    [segment addTarget:self action:@selector(segmentClick:) forControlEvents:UIControlEventValueChanged];
    [self.headView addSubview:segment];
    segment.selectedSegmentIndex = 0;
    
}
/**
 *  创建scrollView
 */
- (void)setUpScrollView{
    //加一个挡板
//    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
//    view.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:view];
    //初始化underScrollView
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    self.scrollView = scrollView;
    scrollView.frame = CGRectMake(0,CGRectGetMaxY(self.segment.frame) + 5, screenW, SCROLL_H);
    
    scrollView.contentSize = CGSizeMake(self.segment.numberOfSegments * screenW, SCROLL_H);
    scrollView.delegate = self;
    scrollView.backgroundColor = BackGroundColor;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    [self.headView addSubview:scrollView];
    [self setUpWebView];
    [self segmentClick:self.segment];
}
/**
 *  初始化webView
 */
- (void)setUpWebView{
    for (int i = 0; i < self.segment.numberOfSegments; i++) {
     UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(screenW * i, 0, screenW, self.scrollView.height - 8)];
//    webView.scrollView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    webView.scalesPageToFit = YES;
    webView.delegate = self;
    webView.scrollView.bounces = YES;
    webView.scrollView.scrollEnabled = NO;
    self.webView = webView;
    webView.tag = WEBVIEW_TAG +i;
    //设置滚动条的显示
    //水平滚动条
    webView.scrollView.showsHorizontalScrollIndicator = NO;
    //垂直滚动条
    webView.scrollView.showsVerticalScrollIndicator = NO;
    [self.scrollView addSubview:webView];
    }
    
}


- (void)setUpTableView{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , 0, screenW,  screenH - 64 ) style:UITableViewStylePlain];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadTableViewData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTableViewData)];
    
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    tableView.footer = footer;
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenW, SEGMENT_H +SCROLL_H +20)];
//    KDLog(@"%@", NSStringFromCGRect(headView.frame));
    headView.backgroundColor = BackGroundColor;
    self.headView = headView;
    tableView.tableHeaderView = headView;
    [self setuUpSegment];
    [self setUpScrollView];
    [self.view addSubview:tableView];
    [tableView.header beginRefreshing];
}
#pragma mark - 网络请求区
/**
 *  请求列表数据
 */
- (void)loadTableViewData{
    self.page = @"1";
    self.param.method = @"getTopicItemList";
    self.param.p = self.page;
    self.param.limit = @"20";
    self.param.business = @"0";
    WS(ws);
    [KDMonitorRequestTool getMonitorListWithParam:self.param WithMainType:5 success:^(KDMKeywordMonitorResult *responseObejct) {
        if ([responseObejct.status isEqualToString:@"notlogin"]) {//如果被别人强制登陆了
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:ws cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.tableView.header endRefreshing];
            
        }else{//正常情况下，就加载数据
            if (!responseObejct.info) {
//                [ws setUpNotise];
                [ws.tableView.header endRefreshing];
                return ;
            }
            ws.infoArr = responseObejct.info;
            if (ws.infoArr.count == 0) {
//                [ws setUpNotise];
            }
            [ws.tableView reloadData];
            [ws.tableView.header endRefreshing];
            [ws.tableView.footer resetNoMoreData];
        }
    } failure:^(NSError *error) {
        [ws.tableView.header endRefreshing];
        KDLog(@"%@",error);
        UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:ws cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [messageView show];
    }];
}
- (void)loadMoreTableViewData{
    self.page = [NSString stringWithFormat:@"%ld",self.page.integerValue +1];
    self.param.method = @"getTopicItemList";
    self.param.p = self.page;
    self.param.limit = @"20";
    
    self.param.sortType = @"0";
    WS(ws);
    [KDMonitorRequestTool getMonitorListWithParam:self.param WithMainType:5 success:^(KDMKeywordMonitorResult *responseObejct) {
        if ([responseObejct.status isEqualToString:@"notlogin"]) {//如果被别人强制登陆了
            //写提示“该账号已在别处登录”
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"该账号已在别处登录" message:@"请重新登录" delegate:ws cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [ws.tableView.header endRefreshing];
            
        }else{//正常情况下，就加载数据
            if (responseObejct.count <= ws.infoArr.count) {
                [ws.tableView.footer endRefreshing];
                return ;
            }
            NSMutableArray *arr = [NSMutableArray arrayWithArray:ws.infoArr];
            [arr addObjectsFromArray: responseObejct.info];
            ws.infoArr = arr;
            [ws.tableView reloadData];
            [ws.tableView.footer endRefreshing];
            if (responseObejct.count <= ws.infoArr.count) {
                [ws.tableView.footer endRefreshing];
            }
            [ws.tableView reloadData];
            [ws.tableView.footer endRefreshing];
            //            KDLog(@"%@", result.info);
        }
    } failure:^(NSError *error) {
        [ws.tableView.footer endRefreshing];
        KDLog(@"%@",error);
        UIAlertView *messageView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败，请检查网络" delegate:ws cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [messageView show];
    }];
}
/**
 *  请求webView的数据
 */
- (void)loadData{
    UIWebView *webView = (UIWebView *)[self.scrollView viewWithTag:WEBVIEW_TAG + self.index];
    NSURLRequest *request;
    NSString *encodedString;
    KDAccount *account = [KDAccountTool account];
    if (self.index && self.webUrl == nil) {//1
        self.webUrl = [NSString stringWithFormat:@"%@mlist_image.html?token=%@&topicId=%@&imageType=1&LoginType=mobile", ServerActionAddr2,account.token, self.param.topicId];
        encodedString = [self.webUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        KDLog(@"%@", self.webUrl);
       request =[NSURLRequest requestWithURL:[NSURL URLWithString:encodedString]];
    }else if (self.mediaUrl == nil){//0
        self.mediaUrl = [NSString stringWithFormat:@"%@mlist_image.html?token=%@&topicId=%@&imageType=0&LoginType=mobile", ServerActionAddr2,account.token, self.param.topicId];
        KDLog(@"%@", self.mediaUrl);
        encodedString = [self.mediaUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        request =[NSURLRequest requestWithURL:[NSURL URLWithString:encodedString]];

    }else{
        [webView.scrollView.header endRefreshing];
        return;
    }
    [webView loadRequest:request];
}
#pragma mark - 事件点击区
- (void)segmentClick:(UISegmentedControl *)segment{
    [self changeOffestWithIndex:(segment.selectedSegmentIndex)];
}
#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [webView.scrollView.header endRefreshing];
    NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];
    [webView stringByEvaluatingJavaScriptFromString:meta];
    
    //修改服务器页面的meta的值
    //    NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];
    //    [webView stringByEvaluatingJavaScriptFromString:meta];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    KDLog(@"%@", error);
    [webView.scrollView.header endRefreshing];
//    if ([error code] != NSURLErrorCancelled) {
//        return;
//    }
}

- (void)changeOffestWithIndex:(NSInteger)index{
    self.index = index;
//    [self transitionWithType:@"FlipFromLeft" WithSubtype:@"kCATransitionFromTop" ForView:self.scrollView];
    if (index) {//如果是在右边
        [UIView transitionWithView:self.scrollView duration:DURATION options:UIViewAnimationOptionTransitionFlipFromRight animations:nil completion:nil];
    }else{//如果是在左边
        [UIView transitionWithView:self.scrollView duration:DURATION options:UIViewAnimationOptionTransitionFlipFromLeft animations:nil completion:nil];
    }
    
    self.scrollView.contentOffset = CGPointMake(screenW *index, self.scrollView.contentOffset.y);
    [self loadData];
}
#pragma CATransition动画实现
- (void) transitionWithType:(NSString *) type WithSubtype:(NSString *) subtype ForView : (UIView *) view
{
    //创建CATransition对象
    CATransition *animation = [CATransition animation];
    
    //设置运动时间
    animation.duration = DURATION;
    
    //设置运动type
    animation.type = type;
    if (subtype != nil) {
        
        //设置子类
        animation.subtype = subtype;
    }
    
    //设置运动速度
    animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;
    
    [view.layer addAnimation:animation forKey:@"animation"];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDRelationCell *cell = [KDRelationCell cellWithTableView:tableView];
    //    KDLog(@"waimian%d", indexPath.row);
    
    if (tableView == self.tableView) {
        cell.delegate = self;
        if (self.infoArr.count != 0) {
            cell.model = self.infoArr[indexPath.row];
            //            KDLog(@"%d\n, title = %@", indexPath.row, cell.model.title);
//            cell.model.parentID = [NSString stringWithFormat:@"%ld", (long)self.homeThemeModel.ID];
        }
        return cell;
    }else{
        return cell;
    }
}

- (CGFloat) tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}
/**
 *  cell被点击了
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    KDMListCellBaseModel * model = self.infoArr[indexPath.row];
    GBSingleWebViewController *singleCtrl = [[GBSingleWebViewController alloc]init];
    singleCtrl.docid = model.docId;
    singleCtrl.titleee = model.title;
    singleCtrl.isCollect = model.isSave;
    singleCtrl.keyword = model.keywords;
    singleCtrl.whichPage = [NSString stringWithFormat:@"%ld",(long)indexPath.row] ;
    singleCtrl.url = model.url;
    singleCtrl.comeFrom = @"1";
    singleCtrl.report = model.isReport;
    singleCtrl.ori_content = model.content;
    singleCtrl.st = model.date;
    singleCtrl.ori_author = model.author;
    singleCtrl.ori_webname = model.source;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:singleCtrl animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

#pragma mark - KDRelationCellDelegate
- (void)KDRelationCell:(KDRelationCell *)cell reportBtnClick:(UIButton *)reportBtn{
    KDMListCellBaseModel * model = cell.model;
    KDReportController *reportCtrl = [[KDReportController alloc]init];
    KDPatrolgetReportParam *param = [[KDPatrolgetReportParam alloc]init];
    param.ori_url = model.url;
    param.ori_title = model.title;
    param.ori_content = model.content;
    param.st = model.date;
    param.doc_id = model.docId;
    if (model.author.length == 0) {
        param.ori_author = nil;
    }else{
        param.ori_author = model.author;
    }
    param.ori_webname = model.source;
    reportCtrl.param = param;
    reportCtrl.type = 2;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:reportCtrl animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
#pragma mark - 页面即将消失时清空缓存
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //清空当前缓存
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [[NSURLCache sharedURLCache] setDiskCapacity:0];
    [[NSURLCache sharedURLCache] setMemoryCapacity:0];
   

}
#pragma mark - UIScrollViewDelegate
//scrollView滑动停止会调动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.scrollView)
    {
        int num = (int)scrollView.contentOffset.x/screenW;
        self.segment.selectedSegmentIndex = num;
        self.index = num;
        [self loadData];
    }
}


@end
